import * as XLSX from 'xlsx';

export const clickExport = (params: any) => {
  const data = [params.titleArr, ...Object.values(params.json).map((element: any) => Object.values(element))];
  // const keyArray = Object.keys(params.json[0]);

  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();

  /* 设置表头高度 */
  const titleHeight = 20;
  ws["!rows"] = [{ hpx: titleHeight }, ...Array(data.length - 1).fill(null).map(() => ({}))];

  /* 隐藏英文字段表头 */
  // const wsrows = [{ hidden: true }];

  /* 设置worksheet每列的最大宽度 */
  const colWidth = data.map(row =>
    row.map(val => ({
      wch: val ? val.toString().charCodeAt(0) > 255 ? val.toString().length * 2 : val.toString().length : 10
    }))
  );

  ws['!cols'] = colWidth[0];
  // ws['!rows'] = wsrows;
  XLSX.utils.book_append_sheet(wb, ws, params.sheetName);

  /* generate file and send to client */
  XLSX.writeFile(wb, `${params.name}.xlsx`);
  
};